package linuxbox.poll.servlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import linuxbox.bean.*;
import linuxbox.common.*;
import linuxbox.poll.logic.*;

public class BoxPollVoteAction
    extends Action
{
  protected static String viewJSP = null;
  protected static String voteJSP = null;
  BoxPoll home = new BoxPoll();

  public void doAction(HttpSession aSession, BoxSession aBoxSession,
                       HttpServletRequest req, HttpServletResponse resp) throws  Exception
  {
    String str = req.getParameter("SubmitCancel");
    if (str != null)
    {
      sendFile(viewJSP, req, resp);
      return;
    }
    int curEntryID = 0;
    str = req.getParameter("ID");
    if (str != null)
    {
      curEntryID = Integer.parseInt(str);
    }
    str = req.getParameter("SubmitView");
    if (str != null)
    {
      viewVotes(curEntryID, req, resp);
      return;
    }
    str = req.getParameter("SubmitVote");
    if (str != null)
    {
      saveVotes(curEntryID, req, aBoxSession);
      viewVotes(curEntryID, req, resp);
      return;
    }
  }

  public boolean saveVotes(int id, HttpServletRequest req,
                           BoxSession aBoxSession)
  {
    String[] choices = req.getParameterValues("CHOICES");
    return home.updateVotes(aBoxSession.getID(), id, choices);
  }

  public void viewVotes(int id, HttpServletRequest req,
                        HttpServletResponse resp) throws IOException, ServletException
  {
    if (id == 0)
    {
      return;
    }

    BoxPollEntry entry = home.get(new BaseIntKey(id));
    if (entry == null)
    {
      //TODO: Log error

      return;
    }

    req.setAttribute("ID", new Integer(id).toString());
    req.setAttribute("SHOWVOTER", entry.getShowVoter() ? "1" : "0");
    req.setAttribute("SHOWRESULT", entry.getShowResult() ? "1" : "0");
    req.setAttribute("MULTIPLE", entry.getMultiple() ? "1" : "0");
    req.setAttribute("SUBJECT", entry.getSubject());
    req.setAttribute("DESCRIPTION", entry.getDescription());

    if (entry.getClosed())
    {
      req.setAttribute("VIEWONLY", "1");
      req.setAttribute("SHOWRESULT", "1");
    }
    else
    {
      req.setAttribute("VIEWONLY", "0");
    }
    sendFile(voteJSP, req, resp);
  }

  public void setViewJSP(String str)
  {
    viewJSP = str;
  }

  public void setVoteJSP(String str)
  {
    voteJSP = str;
  }
}
